package com.qing.transfomer.service;

import com.qing.transfomer.client.QingMappingClient;
import com.qing.transfomer.dto.BaseRequestDTO;
import com.qing.transfomer.dto.mapping.CodeMappingResponseDTO;
import com.qing.transfomer.dto.mapping.CodeMappingResultDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.NoSuchElementException;

@Slf4j
@Service
public abstract class AbstractBaseService {

    @Resource
    private QingMappingClient qingMappingClient;

    public CodeMappingResultDTO getCodeMappingResult(BaseRequestDTO baseRequestDTO) {
        CodeMappingResponseDTO qingMappings = qingMappingClient.getCodes();
        log.info("qingMappings: {}", qingMappings);

        return qingMappings.getCodes().stream()
                .filter(c -> c.getCode().equals(baseRequestDTO.getCode()))
                .findFirst()
                .orElseThrow(() -> {
                    String errorMessage = "Code not found: " + baseRequestDTO.getCode();
                    log.error(errorMessage);
                    return new NoSuchElementException(errorMessage);
                });
    }

    public URI getApplyFilterURI(BaseRequestDTO baseRequestDTO) {
        CodeMappingResultDTO codeMappingResultDTO = getCodeMappingResult(baseRequestDTO);
        return URI.create(baseRequestDTO.getBaseUrl() + "app/" + codeMappingResultDTO.getKey() + "/apply/filter");
    }

    public URI getApplyFilterURI(BaseRequestDTO baseRequestDTO, CodeMappingResultDTO codeMappingResultDTO) {
        return URI.create(baseRequestDTO.getBaseUrl() + "app/" + codeMappingResultDTO.getKey() + "/apply/filter");
    }
}
